/**
 *
 */
package com.sihai.ehr.web.action.ajax;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.sihai.core.Limit;
import com.sihai.core.LimitedList;
import com.sihai.ehr.model.biz.EmployeeinfoWork;
import com.sihai.ehr.utils.StringUtil;
import com.sihai.ehr.web.pojo.EmployeeNoPojo;
import com.sihai.ehr.web.pojo.StaffSearchPojo;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.json.annotations.JSON;

import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.EmployeeinfoBase;
import com.sihai.ehr.service.EmployeeService;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.pojo.EmployeeinfoBasePojo;

/**
 * @author wxn
 * @since 2012-6-16 18:07
 */
public class EmployeeAction extends EHRAction {
	@BeanInject
	private EmployeeService employeeService;

	private String type;
	private String name;
	private Long id;
	private int state;

	private List<EmployeeinfoBase> employees;

	private Long dutyId;

	private int total;
	private int rp;

	private String employeeNo;
	private Long structId;

    private boolean result;

	/**
	 * 员工JSON集
	 */
	private String jsonEmployees;

	private LimitedList<EmployeeinfoBasePojo> basePojos;

	// 查找指定类型的雇员(type: 0为任职人， 1为第一代理 人，2为第二代理人，3为第三代理人)
	@Action(value = "/ajax/proxy_employee", results = { @Result(name = "success", type = "json", params = {
			"root", "employees" }) })
	public String findEmployeeForDutyProxy() {
		employees = employeeService.findForDutyProxy(type, name);
		return SUCCESS;
	}

	/**
	 * 获取员工任职列表
	 * 
	 * @return
	 */
	@Action(value = "/ajax/employee_list", results = { @Result(name = "success", type = "plainText") })
	public String findEmployeeworkList() {
		StaffSearchPojo search = new StaffSearchPojo();
		search.setDepartment(organizationId);
		search.setDuty(dutyId);
		List<EmployeeinfoWork> employeeinfoWorks = employeeService
				.searchEmployeeinfoWorks(search, organizationId, "1",
						createLimit(), createSorter());
		if (employeeinfoWorks != null && employeeinfoWorks.size() > 0) {
			jsonEmployees = employeeWorkInfoToJSON(employeeinfoWorks);
		}
		try {
			HttpServletResponse response = ServletActionContext.getResponse();
			response.getWriter().write(jsonEmployees);
			response.getWriter().flush();
			response.getWriter().close();
			return SUCCESS;
		} catch (Exception e) {
			return null;
		}
	}

	@Action(value = "/ajax/relate_delete", results = { @Result(name = "success", type = "json") })
	public String eduDelete() {
		employeeService.removeEmpRelate(id, state);
		return SUCCESS;
	}

	@Action(value = "/ajax/retrive_workno", results = { @Result(name = "success", type = "json", params = {
			"root", "employeeNo" }) })
	public String getEmployeeNoByOrgId() {
		EmployeeNoPojo workNo = employeeService
				.getEmployeeNoInfoByOrgId(organizationId);
		if (workNo == null) {
			return SUCCESS;
		}
		String currEmployeeNo = employeeService.getEmployeeNo(workNo
				.getEmployeeNo());
		employeeNo = StringUtil.getNextEmployeeNo(currEmployeeNo, workNo);
		return SUCCESS;
	}

	/**
	 * 查询非正式员工集合
	 * 
	 * @return
	 */
	@Action(value = "/ajax/query_noffemployee", results = { @Result(name = "success", type = "plainText") })
	public String queryEmployeeForNOfficial() {
		try {
			Limit mLimit = createLimit();
			basePojos = employeeService.queryEmployeeinfoBasesForNOffical(
					mLimit, createSorter());
			Map map = new HashMap();
			map.put("page", getPage());
			map.put("total", basePojos.getTotalcount());
			jsonEmployees = toJSON(basePojos, map);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.getWriter().write(jsonEmployees);
			response.getWriter().flush();
			response.getWriter().close();

			return SUCCESS;
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 查询薪资结构员工数
	 * @return
	 */
	@Action(value = "/ajax/query_employeeofsalarysid", results = { @Result(name = "success", type = "plainText") })
	public String queryEmployeeNumberBySalaryStructId(){
		try {
			Long totalCount = employeeService.getTotalCountBySalaryStructId(structId);
			HttpServletResponse response = ServletActionContext.getResponse();
			response.getWriter().write(totalCount.toString());
			response.getWriter().flush();
			response.getWriter().close();

			return SUCCESS;
		} catch (Exception e) {
			return null;
		}
	}

	private String toJSON(List list, Map map) {
		List mapList = new ArrayList();
		for (int i = 0; i < list.size(); i++) {
			Map cellMap = new HashMap();
			cellMap.put("id", ((EmployeeinfoBasePojo) list.get(i)).getId());
			cellMap.put(
					"cell",
					new Object[] {
							// "<input type='checkbox'/>",
							((EmployeeinfoBasePojo) list.get(i)).getId(),
							((EmployeeinfoBasePojo) list.get(i)).getName(),
							NumberUtils
									.createInteger(((EmployeeinfoBasePojo) list
											.get(i)).getSex()) > 0 ? "女" : "男",
							((EmployeeinfoBasePojo) list.get(i)).getBirthday() == null ? ""
									: ((EmployeeinfoBasePojo) list.get(i))
											.getBirthday().toString(),
							((EmployeeinfoBasePojo) list.get(i))
									.getCompensation(),
							((EmployeeinfoBasePojo) list.get(i))
									.getCertificate(),
							((EmployeeinfoBasePojo) list.get(i)).getSchool() });
			mapList.add(cellMap);
		}
		map.put("rows", mapList);
		JSONObject object = JSONObject.fromObject(map);
		return object.toString();
	}

	private String employeeWorkInfoToJSON(List<EmployeeinfoWork> works) {
		JSONArray mainJsonArray = new JSONArray();
		for (int i = 0; i < works.size(); i++) {
			JSONObject mJsonObject = new JSONObject();
			mJsonObject.put("workNO", works.get(i).getId());
			mJsonObject.put("name", works.get(i).getBaseId().getName());
			mainJsonArray.add(mJsonObject);
		}
		return mainJsonArray.toString();
	}

	/**
	 * 查询员工职务信息
	 * 
	 * @return
	 */
	@Action(value = "/ajax/query_workinfo", results = { @Result(name = "success", type = "plainText") })
	public String queryEmployeeWorkInfo() {
		try {
			EmployeeinfoWork work = employeeService
					.getEmplyeeinfoWorkByBaseId(id);
			String jsonString = "{\"workno\":\"" + work.getWorkNo()
					+ "\",\"avatar\":\"" + work.getBaseId().getFacePath()
					+ "\"}";
			HttpServletResponse response = ServletActionContext.getResponse();
			response.getWriter().write(jsonString);
			response.getWriter().flush();
			response.getWriter().close();

			return SUCCESS;
		} catch (Exception e) {
			return null;
		}
	}

    //获取员工任职相关信息
    @Action(value = "/ajax/find_work_info", results = { @Result(name = "success",  type = "plainText") })
    public String findEmployeeWorkInfo(){
        EmployeeinfoWork work = null;
        try {
            Long employeeId = NumberUtils.createLong(getParameter("employee_id"));
            work = employeeService.getEmplyeeinfoWorkByBaseId(employeeId);
        } catch (Exception e) {
            e.printStackTrace();
            return SUCCESS;
        }
        if(work != null){
            StringBuffer sb = new StringBuffer();
            sb.append("{");
            sb.append("\"work_id\":").append("\"").append(work.getId()).append("\",");
            sb.append("\"organization_id\":").append("\"").append(work.getOrganization().getId()).append("\",");
            sb.append("\"organization_name\":").append("\"").append(work.getOrganization().getFullName()).append("\",");
            sb.append("\"duty_name\":").append("\"").append(work.getDuty().getDutyName()).append("\",");
            sb.append("\"grade_name\":").append("\"").append(work.getGrade().getGradeName()).append("\",");
            sb.append("\"level_name\":").append("\"").append(work.getGradeLevel().getGradeSort()).append("\"}");
            HttpServletResponse response = ServletActionContext.getResponse();
            try {
                response.getWriter().write(sb.toString());
                response.getWriter().flush();
                response.getWriter().close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return SUCCESS;
    }


    //检查考勤工号是否重复
    @Action(value = "/ajax/check-salary-no", results = { @Result(name = "success", type = "json", params = {"root", "result" }) })
    public String checkSalaryNo(){
        String salaryNo = name;
        if(StringUtils.isBlank(salaryNo)){
            return SUCCESS;
        }
        try {
            EmployeeinfoWork work = employeeService.findBySalaryNo(salaryNo);
            if(work == null || work.getId() == null){ //没有找到,可以添加
                result = true;
            }else{
                if(id != null && id > 0){ //编辑时，找到的是自己的，也可以添加
                    if(id.longValue() == work.getId().longValue()){
                        result = true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }


	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public List<EmployeeinfoBase> getEmployees() {
		return employees;
	}

	public void setEmployees(List<EmployeeinfoBase> employees) {
		this.employees = employees;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public int getState() {
		return state;
	}

	public void setState(int state) {
		this.state = state;
	}

	public Long getDutyId() {
		return dutyId;
	}

	public void setDutyId(Long dutyId) {
		this.dutyId = dutyId;
	}

	@JSON(name = "total")
	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	@JSON(name = "rp")
	public int getRp() {
		return rp;
	}

	public void setRp(int rp) {
		this.rp = rp;
	}

	public String getJsonEmployees() {
		return jsonEmployees;
	}

	public void setJsonEmployees(String jsonEmployees) {
		this.jsonEmployees = jsonEmployees;
	}

	@JSON(name = "rows")
	public LimitedList<EmployeeinfoBasePojo> getBasePojos() {
		return basePojos;
	}

	public void setBasePojos(LimitedList<EmployeeinfoBasePojo> basePojos) {
		this.basePojos = basePojos;
	}

	public String getEmployeeNo() {
		return employeeNo;
	}

	public void setEmployeeNo(String employeeNo) {
		this.employeeNo = employeeNo;
	}
	
	public Long getStructId() {
		return structId;
	}
	
	public void setStructId(Long structId) {
		this.structId = structId;
	}

    public boolean isResult() {
        return result;
    }
}
